package com.hqd.ch03.v18.aop.framework.aspectj;

import com.hqd.ch03.v18.aopalliance.aop.Advice;

import javax.annotation.Nonnull;
import java.lang.reflect.Method;

public abstract class AbstractAspectJAdvice implements Advice {
    private Method aspectJAdviceMethod;
    private Object aspect;
    private AspectJExpressionPointcut pointcut;

    public AbstractAspectJAdvice(AspectJExpressionPointcut pointcut, Method aspectJAdviceMethod, Object aspect) {
        this.aspectJAdviceMethod = aspectJAdviceMethod;
        this.aspect = aspect;
        this.pointcut = pointcut;
    }

    protected void invokeAdviceMethod(@Nonnull Method method) {
        if (match(method)) {
            try {
                aspectJAdviceMethod.invoke(aspect);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 判断是否匹配
     *
     * @param method
     * @return
     */
    protected boolean match(Method method) {
        return pointcut.buildPointcutExpression()
                .matchesMethodExecution(method).alwaysMatches();
    }
}
